<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas width="600" height="600"></canvas>
    <script src="https://cdn.jsdelivr.net/npm/d3-hierarchy@3"></script>
    <script>
        (async function () {
            var canvas = document.querySelector('canvas');
            var ctx = canvas.getContext('2d');

            var data = await (await fetch('./data.json')).json();
            console.log(data);

            // 处理数据
            const regions = d3.hierarchy(data).sum(d => 1).sort((a, b) => b.value - a.value);
            console.log(regions); // 将省份数据按照包含城市的数量，从多到少排序就可以了。
            const pack = d3.pack().size([600, 600]).padding(3); // d3.pack() 将数据映射为一组 1600 宽高范围内的圆形。
            const root = pack(regions);

            console.log(root);
            // 绘图 递归画圆

            function draw(ctx,node,{fillStyle='rgba(0,0,0,.1)',textColor='#333'}={}){
                console.log(node,ctx);
                var children = node.children;
                var {x,y,r} = node;
                console.log(x,y,r);
                ctx.fillStyle = fillStyle;
                ctx.beginPath();
                ctx.arc(x,y,r,0,2*Math.PI);
                ctx.fill();

                // 绘制园内部
                if(children){
                    for(var i = 0;i<children.length;i++){
                        draw(ctx,children[i],{fillStyle:`rgba(0,0,0,${0.1*(node.depth+2)})`})
                    }
                }else{
                    var text = node.data.name;
                    ctx.fillStyle = textColor;
                    ctx.font = '14px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText(text,x,y);
                }
            }
            draw(ctx,root);
        })()


    </script>
</body>

</html>